#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado
import tornado.web
from utils import log
import json
from config import etc
from controls import data_user_info_mysql
from controls import data_journey_base_mysql
from controls import data_journey_info_mysql
from controls import data_journey_image_mysql
from controls import data_journey_mark_mysql
from controls import data_img_base_mysql
from utils.session_base import ApiGuest
from utils.session_mc import BaseHandler

class BrowseHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        userid = self.ss_params['userid']  #userid发起浏览请求的登录用户id
        cityid = self.ss_params['cityid']
        browsed_uids = []
        try :
            browsed_uids_dict = self.ss_params['browsed_uids']
            if browsed_uids_dict : 
                browsed_uids = browsed_uids_dict.values()
        except Exception as e :
            log.exp(e)
        log.i( 'userid=%s, cityid=%s, browsed_uids=%s' % (userid, cityid, browsed_uids) )
        if not (userid and cityid ) : 
            log.w('params fetching error')
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        # need filter userid
        browsed_uids.append(userid)
        
        # get a journey
        journey_base_dict = data_journey_base_mysql.get_journey_base_except_users( cityid, browsed_uids) 
        if not journey_base_dict :
            res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res': {} } 
            self.write( json.dumps(res) )
            self.finish()
            return

        authorid = journey_base_dict['userid']
        
        author_info_dict = data_user_info_mysql.get_user_info_by_userid( authorid )
        journey_base_dict['username'] = author_info_dict['name']
        journey_base_dict['desc'] = author_info_dict['desc']
        log.i(journey_base_dict)
        # markid : {}
        journey_info_dict = data_journey_info_mysql.get_journey_info_all_by_userid( cityid, authorid )
        log.i(journey_info_dict)
        # markid : {}
        journey_mark_dict = data_journey_mark_mysql.get_journey_mark_all_by_userid( cityid, authorid )
        # turn ctime fort
        if journey_mark_dict : 
            for journey_mark in journey_mark_dict.values() : 
                if journey_mark['ctime'] :
                    journey_mark['ctime'] = journey_mark['ctime'].strftime("%Y-%m-%d %H:%M:%S")
        log.i(journey_mark_dict)
        
        # get img group by markid
        journey_image_dict = data_journey_image_mysql.get_journey_image_all_by_cityid_userid( cityid, authorid )
        log.i(journey_image_dict)
        '''
        markid: list
        {
        1: [{'markid' :1, "imgid": 1,"imgurl":"", "ctime": "2015-04-02" }{'markid' :1,"imgid": 1,"imgurl":"", "ctime": "2015-04-02" }]
        2: [{'markid' :2, "imgid": 1,"imgurl":"", "ctime": "2015-04-02" }{'markid' :2,"imgid": 1,"imgurl":"", "ctime": "2015-04-02" }]
        }
        '''
        if journey_image_dict :
            for item_markid in journey_image_dict.values():
                for image_dict in item_markid:
                    imgid = image_dict['imgid']
                    p_item = data_img_base_mysql.get_img_base_by_imgid(imgid)
                    if p_item :
                        image_dict['imgurl'] = 'http://static.shitouren.com/group' + str(p_item['group'])+'/'+str(p_item['path'])+'.'+str(p_item['ext'])
                    else :
                        image_dict['imgurl'] = ''
                '''
                TODO need be delete
                '''
                for image_dict in item_markid:
                    #del image_dict['imgid']
                    del image_dict['userid']
                    del image_dict['markid']

                    
        for markid in journey_info_dict: 
            journey_info_dict[markid].update(journey_mark_dict[markid])
            # if have img
            if journey_image_dict : 
                if markid in journey_image_dict : 
                    journey_info_dict[markid]['image'] = journey_image_dict[markid]
                    
        # sort process
        '''
        xx = {
            1L: {'ctime': '009', 'image': 2, 'ordernum': 9L} ,
            2L: {'ctime': '007', 'image': 2, 'ordernum': 7L} ,
            3L: {'ctime': '008', 'image': 2, 'ordernum': 8L} 
        }'''

        temp = { journey_info_dict[item]['ordernum'] : journey_info_dict[item] for item in journey_info_dict }
        journey_base_dict['journey'] = [ temp[key] for key in sorted(temp.keys())]
        journey_base_dict['cityid'] = cityid

        log.i(journey_base_dict)
        res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':journey_base_dict } 
        self.write( json.dumps(res) )
        self.finish()
        return

'''
[{'username': u'Tomcat', 'title': u'\u6842\u6797\u4e4b\u884c', 'userid': 111L, 'cityid': 1, 
    'journeyid': 1L, 'desc': None, 'utime': '2015-04-27 16:19:23','
    'journey': 
        {'ctime': '2015-04-27 16:19:23', 
        'userid': 111L,  'ordernum': 2L, 'journeyid': 1L, 'sightid': 2L, 'markid': 2L,   'mark': u'\u4eca\u5929\u4e0b\u5348',
        'image': 
            [{'imgname': u'2_2_1.jpg', 'ctime': '2015-04-27 16:26:36', 'imgid': 100000182L, 'imgurl': 'http://static.shitouren.com/group1/M00/00/05/0g6asVU98QuAaaMSAADADEWq7bQ509.jpg'}, 
            {'imgname': u'2_2_2.jpg', 'ctime': '2015-04-27 16:26:44', 'imgid': 100000183L, 'imgurl': 'http://static.shitouren.com/group1/M00/00/05/0g6asVU98QuAc6a9AAChguoDk3k536.jpg'}]}, 
       
       },
]
'''
class BrowseSightHandler( BaseHandler ) :

    @ApiGuest
    def post( self ) :
        userid = self.ss_params['userid']  #userid发起浏览请求的登录用户id
        cityid = self.ss_params['cityid']
        sightid = self.ss_params['sightid']
        start = self.ss_params['start']
        count = 10
        browsed_uids = []
        try :
            browsed_uids_dict = self.ss_params['browsed_uids']
            if browsed_uids_dict : 
                browsed_uids = browsed_uids_dict.values()
        except Exception as e :
            log.exp(e)
        log.i( 'userid=%s, cityid=%s, sightid=%s,browsed_uids=%s' % (userid, cityid, sightid, browsed_uids) )
        if not (userid and cityid and sightid) : 
            log.w('params fetching error')
            res = { 'idx':self.ss_idx, 'ret':1, 'msg':etc.err_500, 'res':{} }
            self.write( json.dumps(res) )
            self.finish()
            return

        # need filter userid
        browsed_uids.append(userid)

        # [{'ordernum': 1L, 'journeyid': 1L, 'sightid': 1L, 'userid': 111L, 'markid': 1L}]
        journey_info_list = data_journey_info_mysql.get_journey_info_except_users( cityid, sightid, browsed_uids, start, count)
        log.i(journey_info_list)
        if not journey_info_list:
            log.w('params fetching error')
            res = { 'idx':self.ss_idx, 'ret':0, 'msg':'ok', 'res':[] }
            self.write( json.dumps(res) )
            self.finish()
            return
        
        res = { 'idx':self.ss_idx, 'ret':0, 'msg': 'ok', 'res':[] }
        journey_list = []
        for journey_info in journey_info_list :
            authorid = journey_info['userid']
            markid = journey_info['markid']
            # get ctime and mark by markid
            # {'markid': 1L, 'userid': 111L, 'ctime': datetime.datetime(2015, 4, 27, 16, 19, 23), 'mark': u'\u4eca\u5929\u4e2d\u5348\u996d\u5802'}
            journey_mark_dict = data_journey_mark_mysql.get_journey_mark_by_userid_markid( cityid, authorid, markid )
            if journey_mark_dict : 
                journey_info['ctime'] = journey_mark_dict['ctime'].strftime("%Y-%m-%d %H:%M:%S") if journey_mark_dict['ctime'] else ''
                journey_info['mark'] = journey_mark_dict['mark']
            log.i(journey_info)

            # get img group by markid
            journey_img_list = data_journey_image_mysql.get_journey_image_all_by_cityid_userid_markid( cityid, authorid, markid )
            log.i(journey_img_list)
            
            if journey_img_list :
                for image_dict in journey_img_list:
                    image_dict['ctime'] = image_dict['ctime'].strftime("%Y-%m-%d %H:%M:%S") if image_dict['ctime'] else ''
                    imgid = image_dict['imgid']
                    p_item = data_img_base_mysql.get_img_base_by_imgid(imgid)
                    if p_item :
                        image_dict['imgurl'] = 'http://static.shitouren.com/group' + str(p_item['group'])+'/'+str(p_item['path'])+'.'+str(p_item['ext'])
                    else :
                        image_dict['imgurl'] = ''
            journey_info['image'] = journey_img_list
            
            journey_item = {'cityid': cityid, 'userid': authorid, 'journeyid': journey_info['journeyid']}
            journey_item['journey'] = journey_info

            # get a journey_base
            journey_base_dict = data_journey_base_mysql.get_journeyid_utime_by_cityid_userid( cityid, authorid ) 
            journey_item['title'] = journey_base_dict['title']
            journey_item['utime'] = journey_base_dict['utime'].strftime("%Y-%m-%d %H:%M:%S") if journey_base_dict['utime'] else ''
            
            # get authorid info
            author_info_dict = data_user_info_mysql.get_user_info_by_userid( authorid )
            if author_info_dict :
                journey_item['username'] = author_info_dict['name']
                journey_item['desc'] = author_info_dict['desc']
            
            journey_list.append(journey_item)
            
        log.i(journey_list)
        res['res'] = journey_list

        self.write( json.dumps(res) )
        self.finish()
        return

class ApiNotFindHandler( BaseHandler ) :
    
    def get( self ):
        raise tornado.web.HTTPError( 503 )
    @tornado.web.asynchronous
    def post( self ):
        log.i( self  )
        res = { 'idx':0, 'ret':9, 'msg':'无此功能', 'res':{} }
        self.write( json.dumps(res) )
        self.finish()
